﻿module Sustainalytics.GovernanceReports.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Routing = Sustainalytics.Routing;

    export interface ICompanyControllerScope extends ng.IScope {
        //open: (size) => void;
    }

    export class ProfileAddController {

        private selectedFile: any;
        private $routeParams: any;
        private newProfileFileName: string;
        private oldProfileFileName: string;
        private oldPublicationDate: string;
        private oldDescription: string;
        //disable save button until the pdf/image upload
        public isSaveDisabled: boolean;

        public publicationDateOpen: boolean = false;

        constructor(
            private $scope: ICompanyControllerScope,
            private $modal: IModal,
            private $modalInstance: IModalInstance,
            private notificationFactory: Common.INotificationFactory,
            private staticObjectsAdmin: CommonAdmin.IStaticObjects,
            private RoutingService: Routing.IRoutingService,
            private companyProfile: GovernanceProfileDto,
            private companyName: string,
            private governanceService: GovernanceService) {

            var ctx = this;
            $scope['profileCompany'] = ctx;

            ctx.$routeParams = RoutingService.getRouteParams();
            ctx.isSaveDisabled = false;

            if (ctx.companyProfile == null) {
                ctx.companyProfile = new GovernanceProfileDto();
                ctx.companyProfile.id = ctx.$routeParams['id'];
                ctx.companyProfile.companyName = companyName;
                var dt = new Date();
                ctx.companyProfile.publicationDate = ('0' + (dt.getMonth() + 1)).slice(-2) + "/" + ('0' + dt.getDate()).slice(-2) + "/" + dt.getFullYear();
            }
            else {
                ctx.oldProfileFileName = ctx.companyProfile.fileName;

                if (ctx.companyProfile.publicationDate == null) {
                    var dt = new Date();
                    ctx.companyProfile.publicationDate = ('0' + (dt.getMonth() + 1)).slice(-2) + "/" + ('0' + dt.getDate()).slice(-2) + "/" + dt.getFullYear();
                } else
                    ctx.oldPublicationDate = ctx.companyProfile.publicationDate;
                ctx.oldDescription = ctx.companyProfile.description;
            }
        }

        public cancel = function (noSave: boolean) {
            var ctx = this;
            if (noSave) {
                ctx.companyProfile.fileName = ctx.oldProfileFileName;
                ctx.companyProfile.publicationDate = ctx.oldPublicationDate;
                ctx.companyProfile.description = ctx.oldDescription;
            }
            ctx.$modalInstance.close({ companyProfile: ctx.companyProfile, noSave: noSave  });
        };

        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjectsAdmin.getMessageByInternalCode(code);
            ctx.notificationFactory.error('', msg);
        }

        // report upload
        public onSelectPdf(files, profile): any {
            var ctx = this;
            ctx.isSaveDisabled = true;
            ctx.companyProfile = profile;
            var file = files[0]; // html assures is just 1
            if (file) {
                if (file.size > 10 * 1024 * 1024 || file.type !== "application/pdf") {
                    ctx.showErrorCode(2108);
                    ctx.isSaveDisabled = false;
                }
                else {
                    ctx.selectedFile = file;
                    //ctx.companyProfile.fileUrl = file.name;

                    var promise = ctx.governanceService.fileUpload(ctx.selectedFile, ctx.companyProfile.fileId);
                    promise.then(
                        //success
                        (data: { id: string; fileUrl: string; filename: string}) => {
                            ctx.$scope.$evalAsync(() => {
                                ctx.companyProfile.fileId = data.id;
                                ctx.companyProfile.fileUrl = data.fileUrl;
                                ctx.newProfileFileName = data.filename;
                                ctx.companyProfile.fileName = null;
                                ctx.notificationFactory.success('Upload succeeded.');
                                ctx.isSaveDisabled = false;
                            });
                        },
                        //error
                        () => {
                            ctx.showErrorCode(2114);
                            ctx.companyProfile.fileName = ctx.oldProfileFileName;
                            ctx.isSaveDisabled = false;
                        }
                   );
                }
            }
        }

        public saveProfile() {
            var ctx = this;

            var message = ctx.validateProfile();

            if (message == "") {
                // save profile
                ctx.companyProfile.fileName = ctx.newProfileFileName;
                var saveProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.saveProfile(ctx.companyProfile);

                saveProfilePromise.then(function (corpData) {
                    ctx.companyProfile = corpData['data'];
                });

                saveProfilePromise.finally(function () {
                    ctx.cancel(false);
                    ctx.notificationFactory.success("Save operation executed successfully.");
                });
            }
            else {
                ctx.notificationFactory.error('', message);
            }
        }

        private validateProfile() {
            var ctx = this;
            var message = "";

            if (ctx.companyProfile.publicationDate == null ||
                ctx.companyProfile.description == null ||
                ctx.companyProfile.fileId == null ||
                (ctx.selectedFile == null && ctx.companyProfile.fileId == null)) {

                message += "Please check the following field(s): ";

                if (ctx.companyProfile.publicationDate == null)
                    message += "<br/> Publication date";
                if (ctx.companyProfile.description == null)
                    message += "<br/> Analyst Summary";
                if (ctx.selectedFile == null && ctx.companyProfile.fileId == null)
                    message += "<br/> Pdf file";
            }
            else {
                var newText = $(ctx.companyProfile.description);
                if (newText.text().length > 3000) {
                    message += "The analyst summary should have maximum 3000 characters.";
                }
            }
            return message;
        }
    }


    export var profileAddControllerName = 'ProfileAddController';

    var mod = angular.module(governanceAdminReportsModuleName);

    mod.controller(profileAddControllerName,
        ['$scope', '$modal', '$modalInstance', 'notificationFactory', 'staticObjectsAdmin', 'RoutingService', 'companyProfile', 'companyName', 'GovernanceService', ProfileAddController]);
}